package cn.com.dcsgo.springcloudstudy.payment.contorller;

import cn.com.dcsgo.springcloudstudy.commons.pojo.CommonResult;
import cn.com.dcsgo.springcloudstudy.commons.pojo.Payment;
import cn.com.dcsgo.springcloudstudy.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 提供restful服务 供其他服务调用
 *
 * @author DCSGO
 * @version 1.0
 */
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${spring.application.name}")
    private String serverName;

    /**
     * 注入服务发现的组件
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取服务信息
     */
    @GetMapping("/payment/discovery")
    public CommonResult<DiscoveryClient> discovery() {
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> instances = discoveryClient.getInstances(serverName);
        for (String s : services) {
            log.info("服务名称:{}", s);
        }
        for (ServiceInstance instance : instances) {
            log.info("服务实例详细信息: ServiceId: {}, Uri: {}, Host: {}, Port:{}", instance.getServiceId(), instance.getUri(), instance.getHost(), instance.getPort());
        }
        return new CommonResult<>(200, "获取服务信息成功", discoveryClient);
    }

    @PostMapping("/payment/create")
    public CommonResult<Long> create(@RequestBody Payment dept) {
        try {
            long id = paymentService.create(dept);
            log.debug("插入成功");
            return new CommonResult<>(200, "插入数据库成功", id);
        } catch (RuntimeException e) {
            return new CommonResult<>(444, "插入数据库失败", null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> queryById(@PathVariable("id") Long id) {
        Payment payment = paymentService.queryById(id);

        if (payment != null) {
            log.info("查询成功 {}", payment);
            return new CommonResult<>(200, "查询成功", payment);
        } else {
            return new CommonResult<>(444, "查询失败", null);
        }
    }

    /**
     * 模拟业务接口超时(延时3s)
     *
     * @return serverName
     */
    @GetMapping("/payment/feign/timeout")
    public String PaymentFeignTimeout() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return serverName;
    }
}
